////////////////////////////////////////////////////////////////////////////////
//  Copyright 2011 Adam Kidd
//  
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//  
//    http://www.apache.org/licenses/LICENSE-2.0
//  
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
////////////////////////////////////////////////////////////////////////////////

package com.arcadefoundry.rest.io
{
	import flash.utils.ByteArray;

	public class ByteBuffer
	{
		//------------------------------------------------
		//
		// Properties
		//
		//------------------------------------------------
		// TODO: Make chunk size configurable?
		/**
		 * The size of the chunks to send over. 
		 */
		private static const CHUNK_SIZE:int = 8192; // 2^13
		
		/**
		 * The bytes in the buffer. 
		 */
		private var bytes:ByteArray;
		
		//------------------------------------------------
		//
		// Constructor
		//
		//------------------------------------------------
		/**
		 * The ByteBuffer is used to read a byte array in sequential chunks.
		 *  
		 * @param bytes The ByteArray to buffer.
		 * 
		 */
		public function ByteBuffer(bytes:ByteArray)
		{
			this.bytes = bytes;
		}
		
		//------------------------------------------------
		//
		// Methods
		//
		//------------------------------------------------
		/**
		 * Reads the next chunk of data from the buffer.
		 *  
		 * @return A new ByteArray containing the next chunk of data.
		 * 
		 */
		public function read():ByteArray
		{
			var chunk:ByteArray = new ByteArray();
			if (bytes.bytesAvailable > 0)
			{
				// Make sure we don't read more than is available.
				var length:uint = Math.min(CHUNK_SIZE, bytes.bytesAvailable);
				bytes.readBytes(chunk, 0, length);
				// Reset the cursor.
				chunk.position = 0;
			}
			return chunk;
		}
		
		//------------------------------------------------
		//
		// Getters & Setters
		//
		//------------------------------------------------
		/**
		 * 
		 * @return The number of bytes left in the buffer.
		 * 
		 */
		public function get bytesAvailable():uint
		{
			return bytes.bytesAvailable;
		}
	}
}
